package com.example.cores_torage;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.cores_torage.entity.User;
import com.example.cores_torage.utils.ToastHelper;
import com.example.cores_torage.utils.UserDBHelper;

public class SqliteCrud extends AppCompatActivity implements View.OnClickListener {
    TextView etName;
    TextView etAge;
    TextView etHeight;
    TextView etWeight;
    CheckBox cbMarried;
    private UserDBHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sqlite_crud);

         etName = findViewById(R.id.et_name);
         etAge = findViewById(R.id.et_age);
         etHeight = findViewById(R.id.et_height);
         etWeight = findViewById(R.id.et_weight);
         cbMarried = findViewById(R.id.cb_married);

         findViewById(R.id.btn_c).setOnClickListener(this);
         findViewById(R.id.btn_r).setOnClickListener(this);
         findViewById(R.id.btn_u).setOnClickListener(this);
         findViewById(R.id.btn_d).setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 获取实例，打开读写链接
        helper = UserDBHelper.getInstance(this);
        helper.openReadLink();
        helper.openWriteLink();
    }

    @Override
    protected void onStop() {
        super.onStop();
        helper.close();
    }

    private void createUser(){
        String name = etName.getText().toString();
        String age = etAge.getText().toString();
        String weight = etWeight.getText().toString();
        String height = etHeight.getText().toString();
        boolean married = cbMarried.isChecked();

        User user = new User(
                name,
                Integer.valueOf(age),
                Long.valueOf(height),
                Float.valueOf(weight),
                married
        );

        boolean res= helper.insert(user) > 0;

        if(res){
            ToastHelper.show(this,"创建成功");
        }else {
            ToastHelper.show(this,"创建失败");
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        // crate
        if(id == R.id.btn_c){
            createUser();
        }
    }
}